<template>
  <!-- 关联渠道订单弹窗 开始 -->
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :append-to-body="false"
    :class="{'mobile-el-dialog': showMobilePage}"
    title=""
    class="large-common-dialog-size related-order-dialog"
    center>
    <div class="main">
      <div class="title-wrap">
        <Title :is-show="true" :total="list.total" font-size="16px" title="关联渠道订单" />
      </div>
      <div class="dialog-scroll">
        <div class="header-form">
          <FilterInput ref="FilterToolRef" v-model="paramsObj" :filter-list="filterList" :is-show-filter="isShowFilter" line-feed show-search-btn @handelClick="queryClick" @queryEmpty="queryEmpty" />
        </div>
        <div v-loading="listLoading" class="table-list">
          <el-row>
            <el-table
              v-if="list && list.items.length"
              ref="orderTable"
              :data="list.items"
              height="345"
              class="fb-table"
              element-loading-text="加载中..."
              empty-text="暂无数据"
              header-cell-class-name="order-data-header-cell"
              fit
              hightlight-current-row>
              <el-table-column
                :fixed="showMobilePage && 'left'"
                align="center"
                label="选择"
                width="50">
                <template slot-scope="scope">
                  <el-radio v-model="orderId" :label="scope.row.id" />
                </template>
              </el-table-column>
              <el-table-column align="left" label="订单类型" width="80">
                <template slot-scope="scope">
                  <div :style="{background: scope.row.bg || 'rgb(253, 239, 233)', color: scope.row.color || 'rgb(253, 133, 70)'}" class="order-type">
                    {{ scope.row.orderType | orderTypeStatusFilter }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="left" label="订单编号" width="200">
                <template slot-scope="scope">
                  <el-tooltip v-if="scope.row.orderInfo.orderId" class="item" placement="top" effect="dark">
                    <div slot="content" class="max-width-200">{{ scope.row.orderInfo.orderId }}</div>
                    <div class="ellipsisOne project-num" @click="goDetail(scope.row.orderInfo.id)">{{ scope.row.orderInfo.orderId }}</div>
                    <!-- <router-link
                      :to="{name: 'orderDetail', params: { orderId: scope.row.orderInfo.id }}"
                      class="project-num"
                    ><div class="ellipsis">{{ scope.row.orderInfo.orderId }}</div></router-link> -->
                  </el-tooltip>
                  <div v-else>--</div>
                </template>
              </el-table-column>
              <el-table-column align="left" label="下单日期" width="110">
                <template slot-scope="scope">
                  <div v-if="scope.row.orderTime">{{ scope.row.orderTime | standardFormatNoHour('YYYY/MM/DD') }}</div>
                  <div v-else>--</div>
                </template>
              </el-table-column>
              <el-table-column align="right" label="含税金额(元)" width="140">
                <template slot-scope="scope">
                  <PriceColumn :real-val="scope.row.taxAmount" :price="scope.row.taxAmount / 100" />
                </template>
              </el-table-column>
              <el-table-column align="left" label="订单状态" width="80">
                <template slot-scope="scope">
                  <div>
                    <div v-if="scope.row.orderStatus || scope.row.orderStatus === 0" >
                      <div :style="{color: getColor(scope.row.orderStatus), textAlign: 'left'}">{{ scope.row.orderStatus | orderStatusFilter }}</div>
                      <!-- 订单状态为封账中(5)时，展示审批状态 -->
                      <div v-if="scope.row.orderStatus === 5" class="review-tag">
                        <el-tag v-if="scope.row.reviewState === 0" size="small" type="success">{{ scope.row.reviewState | setReviewState }}</el-tag>
                        <el-tag v-if="scope.row.reviewState === 1" size="small">{{ scope.row.reviewState | setReviewState }}</el-tag>
                        <el-tag v-if="scope.row.reviewState === 2" size="small" type="danger">{{ scope.row.reviewState | setReviewState }}</el-tag>
                      </div>
                    </div>
                    <span v-else>--</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="left" label="账号" width="120">
                <!-- 账号名称 -->
                <template slot-scope="scope">
                  <div style="display:flex;align-items:center;">
                    <frameContent
                      v-if="scope.row.dataAccount"
                      :platform="scope.row.orderPlatform || scope.row.accountNamePlatform"
                      :data-account="scope.row.dataAccount"
                      :url="scope.row.dataLink"
                      :account-id="scope.row.orderInfo.resourceId"
                      :account-name="scope.row.orderInfo.resourceName" />
                    <resource-info
                      v-if="scope.row.orderInfo.resourceType !== 1 && scope.row.orderInfo.resourceType !== 2"
                      :resource-name="scope.row.resourceName"
                      :account-name-organization="scope.row.accountNameOrganization"
                      :account-name-platform="scope.row.accountNamePlatform"
                      :resource-id="scope.row.orderInfo.resourceCode"
                      account-belong-name="none"
                      style="max-width:calc(100% - 20px);"
                    />
                    <span v-else-if="scope.row.orderInfo.resourceType === 1">多账号</span>
                    <span v-else-if="scope.row.orderInfo.resourceType === 2">无号单</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="left" label="品牌名称" width="100">
                <template slot-scope="scope">
                  <el-tooltip v-if="scope.row.theme" class="item" placement="top" effect="dark">
                    <div slot="content" class="max-width-100">{{ scope.row.theme }}</div>
                    <div class="ellipsis">{{ scope.row.theme }}</div>
                  </el-tooltip>
                  <div v-else>--</div>
                </template>
              </el-table-column>
              <el-table-column align="left" label="下单平台" width="100">
                <!-- 下单平台 -->
                <template slot-scope="scope">
                  <div class="flex-center ellipsisOne">
                    <platformIcon :data="scope.row.orderPlatform" />
                    <div class="ellipsisOne">{{ scope.row.orderPlatform || '--' }}</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="left" label="下单形式" width="100">
                <template slot-scope="scope">
                  <div class="flex-center ellipsisOne">
                    <platformIcon :data="scope.row.orderInfo.orderForm" />
                    <el-tooltip v-if="scope.row.orderForm" class="item" placement="top" effect="dark">
                      <div slot="content" class="max-width-100">{{ scope.row.orderForm }}</div>
                      <div class="ellipsis">{{ scope.row.orderForm }}</div>
                    </el-tooltip>
                    <div v-else>--</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="left" label="所属部门" width="100">
                <template slot-scope="scope">
                  <el-tooltip v-if="scope.row.attributionMatrixName" class="item" placement="top" effect="dark">
                    <div slot="content" class="max-width-100">{{ scope.row.attributionMatrixName }}</div>
                    <div class="ellipsis">{{ scope.row.attributionMatrixName }}</div>
                  </el-tooltip>
                  <div v-else>--</div>
                </template>
              </el-table-column>
              <el-table-column align="left" label="账号归属" width="100">
                <template slot-scope="scope">
                  <el-tooltip v-if="scope.row.orderInfo.accountBelongName" class="item" placement="top" effect="dark">
                    <div slot="content" class="max-width-100">{{ scope.row.orderInfo.accountBelongName }}</div>
                    <div class="ellipsis">{{ scope.row.orderInfo.accountBelongName }}</div>
                  </el-tooltip>
                  <div v-else>--</div>
                </template>
              </el-table-column>
              <el-table-column align="left" label="执行人(商务侧)" width="80">
                <template slot-scope="scope">
                  <el-tooltip v-if="scope.row.orderBusinessOperatorStr" class="item" placement="top" effect="dark">
                    <div slot="content" class="max-width-100">{{ scope.row.orderBusinessOperatorStr }}</div>
                    <div class="ellipsis">{{ scope.row.orderBusinessOperatorStr }}</div>
                  </el-tooltip>
                  <div v-else>--</div>
                </template>
              </el-table-column>
              <el-table-column align="left" label="销售" width="80">
                <template slot-scope="scope">
                  <div>{{ scope.row.market || '--' }}</div>
                </template>
              </el-table-column>
              <el-table-column align="left" label="下单链接" width="100">
                <template slot-scope="scope">
                  <el-tooltip v-if="scope.row.orderInfo.orderLink" class="item" placement="top" effect="dark">
                    <div slot="content"><span class="max-width-100">{{ scope.row.orderInfo.orderLink }}</span></div>
                    <div class="ellipsis">{{ scope.row.orderInfo.orderLink }}</div>
                  </el-tooltip>
                  <div v-else>--</div>
                </template>
              </el-table-column>
            </el-table>
            <empty-placeholder v-else style="margin-bottom: 24px" />
          </el-row>
        </div>
      </div>
      <div class="footer-container">
        <el-button type="primary" size="small" class="submit-btn" @click="relatedOrder">关联订单</el-button>
        <div class="pagination-area">
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            :small="showMobilePage"
            :layout="showMobilePage ? 'total, prev, next, jumper' : 'total, prev, pager, next, sizes, jumper'"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>
  </el-dialog>
  <!-- 关联渠道订单弹窗 -->
</template>

<script>
// 表格列表数据
import { mapState } from 'vuex';
import { hasRouteAuth } from '@/utils/permission';
import { paramsRangeFormat } from '@/utils/paramsFormat';
// 组件
import Title from '@/components/Title';
import FilterInput from '@/components/Tool/filter';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import platformIcon from '@/components/Common/platformIcon';
import frameContent from '@/components/Common/frameContent';
import ResourceInfo from '@/components/ResourceInfo';
// api
import { getList } from '@/api/order';
import { relatedOrder } from '@/api/costManage';
import { platformList, orderFormList } from '@/api/select';
// mixin
import SelectOption from '@/views/order/mixins/selectOption';
// filter
import {
  costTypeFilter,
  orderTypeStatusFilter,
  setReviewState,
  orderStatusFilter } from '@/filters/status';
import { moneyFilter } from '@/filters/number';
import { standardFormatNoHour, format } from '@/filters/date';
// 下拉选项数据
import { orderOption, orderStatusOption } from '@/views/order/model/selectData';

export default {
  name: 'RelatedOrderDialog',
  components: {
    Title,
    FilterInput,
    EmptyPlaceholder,
    platformIcon,
    frameContent,
    ResourceInfo },
  filters: {
    costTypeFilter,
    orderTypeStatusFilter,
    setReviewState,
    moneyFilter,
    standardFormatNoHour,
    format,
    orderStatusFilter },
  mixins: [
    SelectOption],
  props: {
    costId: {
      type: Number,
      default: 0
    },
    relatedOrderId: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      dialogVisible: false,
      isShowFilter: false,
      paramsObj: {},
      orderStatus: '',
      orderId: 0,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true
      },
      page: 1,
      initPerPage: 20,
      listLoading: true,
      orderPlatformOption: [],
      orderFormOption: [],
      rangeKeyArr: [{
        attr: 'orderTime',
        start: 'orderStartTime',
        end: 'orderEndTime',
        type: 'time'
      }, {
        attr: 'taxAmount',
        start: 'taxAmountStart',
        end: 'taxAmountEnd',
        type: 'moneyFixed'
      }]
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    filterList() {
      const arr = [
        // 输入框
        { keyword: 'orderId', name: '订单编号', type: 'input' },
        { keyword: 'theme', name: '品牌名称', type: 'input' },
        { keyword: 'resourceName', name: '账号', type: 'input' },
        { keyword: 'attributionMatrix', name: '所属部门', type: 'input' },
        { keyword: 'accountBelong', name: '账号归属', type: 'input' },
        { keyword: 'orderBusinessOperator', name: '执行人(商务侧)', type: 'input' },
        { keyword: 'market', name: '销售', type: 'input' },
        { keyword: 'taxAmount', name: '含税金额', type: 'inputRange' },
        // 下拉
        { keyword: 'orderFormId', name: '下单形式', type: 'select', emptyText: '请先选择下单平台', options: this.orderFormOption },
        { keyword: 'orderPlatformId', name: '下单平台', type: 'select', options: this.orderPlatformOption },
        { keyword: 'orderType', name: '订单类型', type: 'select', options: orderOption },
        { keyword: 'process', name: '订单状态', type: 'select', options: orderStatusOption },
        // 时间
        { keyword: 'orderTime', name: '下单日期', timeType: 'daterange', type: 'rangeDate' }
      ];
      return arr;
    }
  },
  watch: {
    relatedOrderId() {
      this.orderId = this.relatedOrderId;
    }
  },
  created() {
    this.platformList();
    this.getOrderForm();
  },
  activated() {
  },
  methods: {
    hasRouteAuth,
    handleClose() {
      this.dialogVisible = false;
      this.orderId = 0;
      this.initParams();
      this.$emit('handleClose', '');
    },
    openDialog() {
      this.dialogVisible = true;
      this.orderId = this.relatedOrderId;
      this.fetchData(true);
    },
    initParams() {
      this.paramsObj = {};
    },
    updateList() {
      this.fetchData();
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      // moduleType:用于区分不同页面展示的订单数据 1:成本管理-关联订单
      params.moduleType = 1;
      // 过滤最终单
      params.orderMode = 0;
      paramsRangeFormat(this.rangeKeyArr, params);
      this.listLoading = true;
      getList(this.page, this.list.perPage, params).then(({ data }) => {
        data.items.map(item => { // 添加订单类型的icon,颜色
          const typeImg = this.orderTypeImg.find(currentValue => item.orderType === currentValue.type);
          if (item.orderInfo.orderKind && item.orderInfo.orderKind.length) item.orderInfo.orderKindName = item.orderInfo.orderKind.map(i => i.orderKindName).join('，');
          if (item.orderInfo.orderBusinessOperator && item.orderInfo.orderBusinessOperator.length) {
            item.orderBusinessOperatorStr = item.orderInfo.orderBusinessOperator.map(i => i.userName).join(',');
          }
          item = Object.assign(item, typeImg);
          return item;
        });
        this.list = data;
        this.list.isInit = false;
        this.listLoading = false;
      }).catch(e => {
        if (!e || e.message !== 'cancel') {
          this.listLoading = false;
        }
        console.log(e);
      });
    },
    // 下单平台
    async platformList() {
      try {
        const result = await platformList();
        result.data = result.data.map(item => {
          item = {
            value: item.id,
            label: item.value
          };
          return item;
        });
        result.data.unshift({ value: -2, label: '--' });
        this.orderPlatformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    // 获取下单形式
    getOrderForm(orderPlatformId) {
      orderFormList(orderPlatformId).then(res => {
        res.data.forEach(i => {
          i.label = i.value;
          i.value = i.id;
        });
        this.orderFormOption = res.data;
      }, result => {
        // this.$message.error(result.message);
      });
    },
    // 查询
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.list.perPage = val;
      this.fetchData(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    // 关联订单
    relatedOrder() {
      const { orderId, costId } = this;
      if (!orderId) {
        this.$message.warning('请选择要关联的渠道订单！');
        return false;
      }
      const params = {
        relatedOrderId: orderId,
        costId
      };
      relatedOrder(params).then(res => {
        this.$message.success('关联成功');
        // 将选择的订单id传送给父组件
        this.$emit('relatedOrder', orderId);
        this.handleClose();
      }).catch(err => {
        console.error(err);
      });
    },
    goDetail(orderId) {
      const routeUrl = this.$router.resolve({
        name: 'orderDetail',
        params: {
          orderId
        }
      });
      window.open(routeUrl.href, '_blank');
    },
    getColor(stauts) {
      // 订单状态： 0: 草稿中 1: 待发布 2: 待核算 3: 待审批 4: 待封账 5: 封账中 6: 已封账 7: 已完成
      let color = '';
      switch (stauts) {
        case 0:
          color = '#406EFF';
          break;
        case 5:
          color = '#FD8546';
          break;
        case 7:
          color = '#31CC9C';
          break;
      }
      return color;
    }
  }
};
</script>

<style lang="scss" scoped>
.related-order-dialog {
  ::v-deep {
    .el-dialog__body {
      padding: 10px 25px 0;
    }
    .el-icon {
      color: #999;
    }
    .el-radio__label {
      display: none;
    }
    .select-input-component .el-input>.el-input__inner {
      width: 160px;
    }
  }
}
.el-pagination {
  padding: 0 !important;
}
.main {
  position: relative;
  height: 485px;
}
.header-form {
  position: relative;
  margin-bottom: 24px;
}
.title-wrap {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 24px;
}
.table-list {
  min-height: 300px;
}
.max-width-100 {
  max-width: 100;
}
.max-width-200 {
  max-width: 200px;
}
.order-type {
  width: 56px;
  height: 20px;
  border-radius: 16px;
  font-size: 12px;
  display: flex;
  justify-content: center;
  align-content: center;
  align-items: center;
  img {
    width: 16px;
    height: 16px;
    margin-right: 6px;
  }
}
.review-tag {
  display:flex;
  justify-content: center;
}
.project-num {
  cursor: pointer;
  color: #406EFF;
}
.el-table::before {
  display: none;
}
.dialog-scroll {
  height: 405px;
  @include scrollBar();
}
.submit-btn {
  height: 30px;
}
.footer-container{
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 10px;
}
.mobile-el-dialog {
  &.related-order-dialog {
    ::-webkit-scrollbar {
      width: 8px !important;
    }
  .footer-container {
    overflow-x: auto;
    ::v-deep .el-pagination__jump {
      margin-left: 0;
    }
    .submit-btn {
      margin-right: 5px;
    }
  }
    .header-form {
      margin-bottom: 8px;
    }
    .main {
      height: fit-content;
    }
    .dialog-scroll {
      height: fit-content;
    }
    ::v-deep .select-input-component {
      .el-input>.el-input__inner {
        width: 100%;
      }
    }
  }
}
</style>
